package com.zzx.controller;

import com.alibaba.fastjson2.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zzx.common.domain.CommonResult;
import com.zzx.pojo.Goods;
import com.zzx.pojo.User;
import com.zzx.pojo.UserOrder;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/10/4 10:57
 */
@Tag(name = "商城控制器", description = "商城模块")
@RestController
@RequestMapping("easyshop")
public class EasyShopController
{
    @Value("${easyshop.user-service-name}")
    private String userServiceName;

    @Value("${easyshop.goods-service-name}")
    private String goodsServiceName;

    @Value("${easyshop.order-service-name}")
    private String orderServiceName;

    @Resource
    private RestTemplate restTemplate;//提供多种便捷访问远程http服务的方法，简单的Restful服务模板~


    /**
     * getGoodsByGoodsId
     * @param goodsId
     * @return
     */
    @Tag(name = "商城控制器")
    @HystrixCommand(commandKey = "getGoodsByGoodsId",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixGetGoodsByGoodsId"
    )
    @GetMapping("/getGoodsByGoodsId")
    public CommonResult getGoodsByGoodsId(@RequestParam("goodsId") Integer goodsId)
    {
        System.out.println(4001);
        return restTemplate.getForObject(goodsServiceName + "/goods/getGoodsById/" + goodsId, CommonResult.class);
    }

    public CommonResult hystrixGetGoodsByGoodsId(@RequestParam("goodsId") Integer goodsId)
    {
        return CommonResult.error().message("找不到对应的商品，请要求客服正确 .........");
    }


    /**
     * 获得商品列表
     *
     * @return
     */
    @Tag(name = "商城控制器")
    @HystrixCommand(commandKey = "list",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixList"
    )
    @GetMapping("/list")
    public CommonResult list()
    {
        System.out.println(4001);
        return restTemplate.getForObject(goodsServiceName + "/goods/getGoodsList", CommonResult.class);
    }

    public CommonResult hystrixList()
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

    @Tag(name = "商城控制器")
    @HystrixCommand(commandKey = "addOrder",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixAddOrder"
    )
    @PostMapping("/addOrder")
    public CommonResult addOrder(@RequestBody UserOrder userOrder)
    {
        // 检查是否有未完成同商品的订单
        CommonResult isExist = restTemplate.getForObject(orderServiceName + "/order/getOnesExistOrder?userId=" + userOrder.getUserId() + "&goodsId=" + userOrder.getGoodsId(), CommonResult.class);
        List<UserOrder> userOrders = JSON.parseArray(JSON.toJSONString(isExist.getData().get("userOrders")), UserOrder.class);
        if (userOrders.size() > 0)
        {
            return CommonResult.error();
        } else
        {
            // 制成订单
            restTemplate.postForObject(orderServiceName + "/order/makeOrder", userOrder, CommonResult.class);
            // 减少商品
            CommonResult goodsResult = restTemplate.getForObject(goodsServiceName + "/goods/getGoodsById/" + userOrder.getGoodsId(), CommonResult.class);
            Goods goods = JSON.parseObject(JSON.toJSONString(goodsResult.getData().get("goods")), Goods.class);
            goods.setGoodsNum(goods.getGoodsNum() - userOrder.getBuyNum());
            restTemplate.put(goodsServiceName + "/goods/editGoodsNum", goods, CommonResult.class);
            return CommonResult.ok();
        }
    }

    public CommonResult hystrixAddOrder(@RequestBody UserOrder userOrder)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

    @Tag(name = "商城控制器")
    @HystrixCommand(commandKey = "getOnesOrderList",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixGetOnesOrderList"
    )
    @GetMapping("/getOnesOrderList")
    public CommonResult getOnesOrderList(@RequestParam("userId") Integer userId, @RequestParam("orderState") String orderState)
    {
        return restTemplate.getForObject(orderServiceName + "/order/getOnesOrderList?userId=" + userId + "&orderState=" + orderState, CommonResult.class);
    }

    public CommonResult hystrixGetOnesOrderList(@RequestParam("userId") Integer userId, @RequestParam("orderState") String orderState)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

    @Tag(name = "商城控制器")
    @HystrixCommand(commandKey = "cancelOrder",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixCancelOrder"
    )
    @PutMapping("/cancelOrder")
    public CommonResult cancelOrder(@RequestBody UserOrder userOrder)
    {
        restTemplate.put(orderServiceName + "/order/cancelOrder", userOrder, CommonResult.class);
        CommonResult goodsResult = restTemplate.getForObject(goodsServiceName + "/goods/getGoodsById/" + userOrder.getGoodsId(), CommonResult.class);
        Goods goods = JSON.parseObject(JSON.toJSONString(goodsResult.getData().get("goods")), Goods.class);
        goods.setGoodsNum(goods.getGoodsNum() + userOrder.getBuyNum());
        restTemplate.put(goodsServiceName + "/goods/editGoodsNum", goods, CommonResult.class);
        return CommonResult.ok();
    }

    public CommonResult hystrixCancelOrder(@RequestBody UserOrder userOrder)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }

    @Tag(name = "商城控制器")
    @PutMapping("/payOrder")
    @HystrixCommand(commandKey = "payOrder",
            commandProperties = {
                    @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500"),
            },
            fallbackMethod = "hystrixPayOrder"
    )
    public CommonResult payOrder(@RequestBody UserOrder userOrder)
    {
        restTemplate.put(orderServiceName + "/order/payOrder", userOrder, CommonResult.class);
        // 减少用户余额
        CommonResult userResult = restTemplate.getForObject(userServiceName + "/user/getUserById/" + userOrder.getUserId(), CommonResult.class);
        User user = JSON.parseObject(JSON.toJSONString(userResult.getData().get("user")), User.class);
        CommonResult goodsResult = restTemplate.getForObject(goodsServiceName + "/goods/getGoodsById/" + userOrder.getGoodsId(), CommonResult.class);
        Goods goods = JSON.parseObject(JSON.toJSONString(goodsResult.getData().get("goods")), Goods.class);
        user.setUserBalance(user.getUserBalance() - (long) userOrder.getBuyNum() * goods.getGoodsPrice());
        restTemplate.put(userServiceName + "/user/editUserBalance", user, CommonResult.class);
        return CommonResult.ok();
    }

    public CommonResult hystrixPayOrder(@RequestBody UserOrder userOrder)
    {
        return CommonResult.error().message("服务器开小差了~~~");
    }


}